#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    currentw=nullptr;
    // timer=new QTimer(this);
    // timer->start(12*1000);
    // connect(timer,&QTimer::timeout,this,&MainWindow::onTimerTimeOut);

    //设置主窗口圆角
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);
    resize(1200,800);
    setMinimumWidth(800);

    //https
    https=new Https(this);

    //poplist
    poplistw=new PopupListWidget(this);
    poplistw->hide();
    connect(poplistw,&QListWidget::itemClicked,this,&MainWindow::onItemClicked);

    //listw
    listw=new ListWidget(this);
    connect(this,&MainWindow::albumName,listw,&ListWidget::AddCreatePlayList1);
    connect(listw,&ListWidget::clickedButton,this,&MainWindow::onClickListWidgetButton);

    //title
    title=new TitleBar(this);
    title->setGeometry(0,0,this->width(),75);
    connect(title,&TitleBar::searchSignal,this,&MainWindow::onSearchRequest);

    auto searchlistw=title->GetSearchListW();
    searchlistw->addHistory(QStringList()<<"跳楼机"<<"Ave Mujica"<<"on the edge"<<"一半");
    searchlistw->UpDataHistoryBack();
    searchlistw->addHot(QStringList()<<"跳楼机"<<"唯一"<<"OH MY GIRL"<<"你"<<"wasted");
    searchlistw->UpDataHot();
    title->SetPlaceholderText(QStringList()<<"塞壬唱片-MSR"<<"跳楼机"<<"唯一");
    connect(title,&TitleBar::minSignal,this,&MainWindow::showMinimized);
    connect(title,&TitleBar::maxSignal,this,&MainWindow::showMaximized);
    connect(title,&TitleBar::closeSignal,this,&MainWindow::close);
    connect(title,&TitleBar::windowingSignal,this,[this]{this->showNormal();});
    connect(title,&TitleBar::userNameSignal,this,&QWidget::show);

    //createnew
    createnew=new CreateNewAlbum(this);
    createnew->hide();
    connect(createnew,&CreateNewAlbum::ok,this,&MainWindow::onCreateNewAlbum);
    connect(listw,&ListWidget::createPlayList,createnew,&CreateNewAlbum::show);

    bottomw=new BottomWidget(this);
    connect(bottomw,&BottomWidget::newMainWindowSize,this,&MainWindow::onNewMainWindow);

    //loginWidget
    loginw=new LoginWidget;
    loginw->show();
    connect(loginw,&LoginWidget::login,this,&MainWindow::onLoginRequest);//登录
    connect(https,&Https::loginResponse,this,&MainWindow::onLoginResponse);

    //recommendw
    recommendw=new AlbumWidget(this);
    recommendw->hide();
    connect(listw,&ListWidget::recommendWidget,this,&MainWindow::onRecommendShow);


    //localmusicwidget
    localmusicw=new LocalMusicWidget(this);
    localmusicw->setGeometry(200,75,1000,650);
    localmusicw->hide();
    connect(localmusicw,&AlbumWidget::getSongInfo,https,&Https::sendGetRequest);
    connect(listw,&ListWidget::localMusicWidget,this,&MainWindow::onLocalMusicShow);

    //mylikew
    mylikew=new AlbumWidget(this);
    connect(listw,&ListWidget::myLikeWidget,this,&MainWindow::onMyLikeShow);
    // currentw->setGeometry(200,75,1000,650);
    // connect(currentw,&AlbumWidget::playSignal,bottomw,&BottomWidget::onPlaySignal);
    // connect(currentw,&AlbumWidget::getSongInfo,https,&Https::sendGetRequest);
    // connect(https,&Https::albumInfoReady,currentw,&AlbumWidget::onHttpsAlubmInfo);
    // connect(https,&Https::songInfoReady,currentw,&AlbumWidget::onSongInfoReady);
    // connect(bottomw,&BottomWidget::endSignal,currentw,&AlbumWidget::onNextSong);
    // connect(bottomw,&BottomWidget::nextSignal,currentw,&AlbumWidget::onNextSong);
    // connect(bottomw,&BottomWidget::previousSignal,currentw,&AlbumWidget::onPreviousSong);

    //historymusicw
    historymusicw=new HistoryMusicWidget(this);
    historymusicw->setGeometry(200,75,1000,650);
    historymusicw->hide();
    connect(listw,&ListWidget::historyMusicWidget,this,&MainWindow::onHistoryShow);

    //searchmusicw
    searchmusicw=new SearchMusicWidget(this);
    searchmusicw->hide();
    connect(https,&Https::searchInfoReady,this,&MainWindow::onSearchResponse);

    //test
    QStringList strlist;
    strlist<<"薛之谦"<<"天外来物"<<"暧昧"<<"动物世界"<<"像风一样";
    title->GetSearchListW()->addSearch(strlist);
    title->GetSearchListW()->UpDataSearch();

    //https->sendGetRequest("http://127.0.0.1:8080/album/100");

    //正式
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::SetCurrentWidget(AlbumWidget*w)
{
    //断开之前的连接
    if(currentw!=nullptr)
    {
        currentw->hide();
        disconnect(currentw,&AlbumWidget::playSignal,bottomw,&BottomWidget::onPlaySignal);
        disconnect(currentw,&AlbumWidget::playSignal,historymusicw,&HistoryMusicWidget::addNewRecord);
        disconnect(currentw,&AlbumWidget::getSongInfo,https,&Https::sendGetRequest);
        disconnect(currentw,&AlbumWidget::flush,this,&MainWindow::onFlush);
        disconnect(currentw,&AlbumWidget::deleteSongSignal,this,&MainWindow::onDeleteSongItem);
        disconnect(currentw,&AlbumWidget::downloadSignal,this,&MainWindow::onDownload);
        disconnect(https,&Https::albumInfoReady,currentw,&AlbumWidget::onHttpsAlubmInfo);
        disconnect(https,&Https::songInfoReady,currentw,&AlbumWidget::onSongInfoReady);
        disconnect(bottomw,&BottomWidget::endSignal,currentw,&AlbumWidget::onNextSong);
        disconnect(bottomw,&BottomWidget::nextSignal,currentw,&AlbumWidget::onNextSong);
        disconnect(bottomw,&BottomWidget::previousSignal,currentw,&AlbumWidget::onPreviousSong);

    }

    currentw=w;
    currentw->setGeometry(200,75,1000,650);
    currentw->onMainWindowResize(size());
    if(!currentw->Ready())
        https->sendGetRequest("http://127.0.0.1:8080/album/"+QString::number(currentw->AlbumId()));
    currentw->show();
    connect(currentw,&AlbumWidget::playSignal,bottomw,&BottomWidget::onPlaySignal);
    connect(currentw,&AlbumWidget::playSignal,historymusicw,&HistoryMusicWidget::addNewRecord);
    connect(currentw,&AlbumWidget::getSongInfo,https,&Https::sendGetRequest);
    connect(currentw,&AlbumWidget::flush,this,&MainWindow::onFlush);
    connect(currentw,&AlbumWidget::deleteSongSignal,this,&MainWindow::onDeleteSongItem);
    connect(currentw,&AlbumWidget::favorSongSignal,this,&MainWindow::onFavorSong);
    connect(currentw,&AlbumWidget::downloadSignal,this,&MainWindow::onDownload);
    connect(https,&Https::albumInfoReady,currentw,&AlbumWidget::onHttpsAlubmInfo);
    connect(https,&Https::songInfoReady,currentw,&AlbumWidget::onSongInfoReady);
    connect(bottomw,&BottomWidget::endSignal,currentw,&AlbumWidget::onNextSong);
    connect(bottomw,&BottomWidget::nextSignal,currentw,&AlbumWidget::onNextSong);
    connect(bottomw,&BottomWidget::previousSignal,currentw,&AlbumWidget::onPreviousSong);
}

void MainWindow::onLoginRequest(const QString&useridstr,const QString&password)
{
    QJsonObject obj;
    userid=useridstr.toLongLong();
    obj["user_id"]=userid;
    obj["password"]=password;
    https->sendPostRequest("http://127.0.0.1:8080/login",obj);
}

void MainWindow::onLoginResponse(const QJsonObject&obj)
{
    if(obj["message"].toString()=="success")
    {
        loginw->hide();
        title->SetUserName(obj["data"]["user_name"].toString());
        title->SetHeadShot("./preview.jpg");
        QJsonArray jsonarr=obj["data"]["recommend"].toArray();
        QVector<SongItem*>songitems;
        for(auto it=jsonarr.begin();it!=jsonarr.end();it++)
        {
            QJsonObject obj;
            obj["song_id"]=it->toInt();
            songitems.push_back(SongItem::FromJsonOBJect(obj));
        }
        recommendw->AddSongItem(songitems);
        recommendw->SetAlbumInfo(0,"推荐","");

        qint64 myfavor=obj["data"]["my_favorite"].toInteger();
        QJsonArray jsonarrname=obj["data"]["album_name"].toArray();
        QJsonArray jsonarrid=obj["data"]["album_id"].toArray();
        QStringList strlist;
        for(qint32 i=0;i<jsonarrname.size();i++)
        {
            if(myfavor!=jsonarrid[i].toInteger())
            {
                auto ptr=new AlbumWidget(this);
                ptr->hide();
                ptr->SetAlbumId(jsonarrid[i].toInteger());
                albums.push_back(ptr);
                strlist<<jsonarrname[i].toString();
            }
            else
            {
                mylikew->SetAlbumId(myfavor);
            }
        }
        qDebug()<<strlist;
        emit albumName(strlist);

        SetCurrentWidget(mylikew);

        //显示
        this->show();
    }
    else
    {
        QMessageBox::information(this,"登陆失败","密码或账号错误");
    }
}

void MainWindow::onSearchRequest(const QString&text)
{
    QJsonObject obj;
    obj["searchmessage"]=text;
    https->sendPostRequest("http://127.0.0.1:8080/search",obj);
}

void MainWindow::onSearchResponse(const QJsonObject&obj)
{
    searchmusicw->clean();
    QJsonArray arr=obj["data"].toArray();
    QVector<SongItem*>songitems;
    for(auto elem:arr)
    {
        auto ptr=SongItem::FromUrl(QUrl("http://127.0.0.1:8080/songs/"+QString::number(elem.toInt())+".mp3"));
        songitems.push_back(ptr);
    }
    searchmusicw->AddSongItem(songitems);
    SetCurrentWidget(searchmusicw);
}

void MainWindow::onNewMainWindow(const QSize& newsize)
{
    resize(newsize);
}

void MainWindow::onDeleteSongItem(qint64 albumid,qint64 songid)
{
    QJsonObject obj;
    obj["song_id"]=songid;
    obj["albumid"]=albumid;
    https->sendPostRequest("http://127.0.0.1:8080/songsfromalbum",obj);
}

void MainWindow::onFavorSong(qint64 songid)
{
    poplistw->clear();
    poplistw->addItems(QStringList()<<"我喜欢的音乐"<<listw->StringList());
    poplistw->show();
    tmp=songid;
}

void MainWindow::onItemClicked(QListWidgetItem*item)
{
    QJsonObject obj;

    auto ptr=SongItem::FromUrl("http://127.0.0.1:8080/songs/"+QString::number(tmp));
    qint64 albumid;
    QVector<SongItem*>vec{ptr};
    if(item->text()=="我喜欢的音乐")
    {
        mylikew->AddSongItem(vec);
        albumid=mylikew->AlbumId();
    }
    auto strlist=listw->StringList();
    for(qint32 i=0;i<strlist.size();i++)
    {
        if(strlist[i]==item->text())
        {
            albums[i]->AddSongItem(vec);
        }
    }
    obj["song_id"]=tmp;
    obj["album_id"]=albumid;
    https->sendPostRequest("http://127.0.0.1:8080/songstoalbum",obj);
    poplistw->hide();
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    listw->onMainWindowResize(event->size());
    title->onMainWindowResize(event->size());
    bottomw->onMainWindowResize(event->size());
    localmusicw->onMainWindowResize(event->size());
    currentw->onMainWindowResize(event->size());
    qDebug()<<size();
}

void MainWindow::paintEvent(QPaintEvent *e)
{
    Q_UNUSED(e)
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(QColor("#f0f3f6")); // 背景颜色
    painter.setPen(Qt::NoPen); // 无边框
    painter.drawRoundedRect(this->rect(), 10, 10);
}

void MainWindow::mousePressEvent(QMouseEvent*e)
{
    QMainWindow::mousePressEvent(e);
    setFocus();
}

void MainWindow::onLocalMusicShow()
{
    SetCurrentWidget(localmusicw);
}

void MainWindow::onMyLikeShow()
{
    SetCurrentWidget(mylikew);
}

void MainWindow::onRecommendShow()
{
    SetCurrentWidget(recommendw);
}
void MainWindow::onHistoryShow()
{
    SetCurrentWidget(historymusicw);
}

void MainWindow::onFlush()
{
    if(on)
        resize(size().width()+1,size().height()+1);
    else
        resize(size().width()-1,size().height()-1);
    on=!on;
}

void MainWindow::onCreateNewAlbum()
{
    QString albumname=createnew->AlbumName();
    QString tags=createnew->Tags();
    QString intro=createnew->Intro();

    //mainwindow操作
    auto ptr=new AlbumWidget(this);
    albums.push_back(ptr);
    ptr->SetAlbumInfo(0,albumname,intro);

    //ListWidget操作
    listw->AddCreatePlayList1(QStringList()<<albumname);

    //发送服务请求
    QJsonObject obj;
    obj["album_name"]=albumname;
    obj["creator_id"]=userid;
    obj["tags"]=tags;
    obj["intro"]=intro;
    obj["create_date"]=QDate::currentDate().toString("yyyy-MM-dd");
    obj["my_favorite"]=false;
    https->sendPostRequest("http://127.0.0.1:8080/createalbum",obj);
    connect(https,&Https::albumidReady,ptr,&AlbumWidget::onAlbumid);

}

void MainWindow::onClickListWidgetButton(qint32 order)
{
    SetCurrentWidget(albums[order]);
}

void MainWindow::onDownload(const QVector<SongItem*>&songitems)
{
    qDebug()<<QFileDialog::getExistingDirectory();
}

